package com.fengxu.netty.detectconnect;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

// 测试Netty心跳检测机制的服务器
public class IdleTestServer {

    public static void main(String[] args) throws InterruptedException {

        // 创建线程组
        NioEventLoopGroup boosGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        // 创建服务器启动器
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boosGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,128)
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        /** IdleStateHandler是netty提供的处理空闲状态的处理器
                         *  readerIdleTime: 表示多长时间没有触发读取事件
                         *  writerIdleTime: 表示多长时间没有发生写事件
                         *  allIdleTime: 表示多长内有发生读和写事件
                         *  TimeUnit.SECONDS: 时间单位(分钟)
                         */
                        ch.pipeline()
                          .addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS));
                        // 加入对空闲检测进行处理的handler,当IdleStateHandler触发后，会将结果返回值管道的下一个handler
                        // 可以通过实现Handler中的userEventTrigger来得到上一个管道传来的数据
                        ch.pipeline().addLast(new MyHandler());
                    }
                });

        serverBootstrap.bind(6666).sync()
                .channel().closeFuture().sync();
    }

    private static class MyHandler extends ChannelInboundHandlerAdapter{

        // 得到IdleStateHandler传来的数据,evt事件类型
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if(evt instanceof IdleStateEvent){
                IdleStateEvent event = (IdleStateEvent) evt;
                String eventType = null;
                switch (event.state()){
                    case ALL_IDLE:
                        eventType = "读写空闲";
                        break;
                    case READER_IDLE:
                        eventType = "读空闲";
                        break;
                    case WRITER_IDLE:
                        eventType = "写空闲";
                        break;
                }
                System.out.println("触发事件："+eventType);
            }
        }
    }
}
